<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="技术博客">
    
    <meta name="author" content="jiesun">
    <!-- preconnect -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    
    
    <!--- Seo Part-->
    
    <link rel="canonical" href="https://anca.gitee.io/2023/11/04/module/"/>
    <meta name="robots" content="index,follow">
    <meta name="googlebot" content="index,follow">
    <meta name="revisit-after" content="1 days">
    
        <meta name="description" content="vite是esm而webpack是commonjs，有什么区别呢">
<meta property="og:type" content="article">
<meta property="og:title" content="搞懂模块化">
<meta property="og:url" content="https://anca.gitee.io/2023/11/04/module/index.html">
<meta property="og:site_name" content="孙杰的博客">
<meta property="og:description" content="vite是esm而webpack是commonjs，有什么区别呢">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-11-04T06:50:37.195Z">
<meta property="article:modified_time" content="2023-11-04T07:31:15.727Z">
<meta property="article:author" content="jiesun">
<meta property="article:tag" content="技术博客">
<meta name="twitter:card" content="summary">
    
    
    <!--- Icon Part-->
    <link rel="icon" type="image/png" href="/jiesun.gitee.io/images/redefine-favicon.svg" sizes="192x192">
    <link rel="apple-touch-icon" sizes="180x180" href="/jiesun.gitee.io/images/redefine-favicon.svg">
    <meta name="theme-color" content="#A31F34">
    <link rel="shortcut icon" href="/jiesun.gitee.io/images/redefine-favicon.svg">
    <!--- Page Info-->
    
    <title>
        
            搞懂模块化 -
        
        极乐净土
    </title>
    
<link rel="stylesheet" href="/jiesun.gitee.io/css/style.css">


    
        
<link rel="stylesheet" href="/jiesun.gitee.io/css/build/styles.css">

    

    
<link rel="stylesheet" href="/jiesun.gitee.io/fonts/fonts.css">

    
<link rel="stylesheet" href="/jiesun.gitee.io/fonts/Satoshi/satoshi.css">

    
<link rel="stylesheet" href="/jiesun.gitee.io/fonts/Chillax/chillax.css">

    <!--- Font Part-->
    
    
    
    

    <!--- Inject Part-->
    
    <script id="hexo-configurations">
    let Global = window.Global || {};
    Global.hexo_config = {"hostname":"anca.gitee.io","root":"/jiesun.gitee.io/","language":"zh-CN"};
    Global.theme_config = {"articles":{"style":{"font_size":"16px","line_height":1.5,"image_border_radius":"14px","image_alignment":"center","image_caption":false,"link_icon":true},"word_count":{"enable":true,"count":true,"min2read":true},"author_label":{"enable":true,"auto":false,"list":[]},"code_block":{"copy":true,"style":"mac","font":{"enable":false,"family":null,"url":null}},"toc":{"enable":true,"max_depth":3,"number":false,"expand":true,"init_open":true},"copyright":true,"lazyload":true,"recommendation":{"enable":false,"title":"推荐阅读","limit":3,"mobile_limit":2,"placeholder":"/images/wallhaven-wqery6-light.webp","skip_dirs":[]}},"colors":{"primary":"#A31F34","secondary":null},"global":{"fonts":{"chinese":{"enable":false,"family":null,"url":null},"english":{"enable":false,"family":null,"url":null}},"content_max_width":"1000px","sidebar_width":"210px","hover":{"shadow":true,"scale":false},"scroll_progress":{"bar":false,"percentage":true},"website_counter":{"url":"https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js","enable":true,"site_pv":true,"site_uv":true,"post_pv":true},"single_page":true,"open_graph":true,"google_analytics":{"enable":false,"id":null}},"home_banner":{"enable":true,"style":"fixed","image":{"light":"/images/wallhaven-wqery6-light.webp","dark":"/images/wallhaven-wqery6-dark.webp"},"title":"极乐净土","subtitle":{"text":[],"hitokoto":{"enable":false,"api":"https://v1.hitokoto.cn"},"typing_speed":100,"backing_speed":80,"starting_delay":500,"backing_delay":1500,"loop":true,"smart_backspace":true},"text_color":{"light":"#fff","dark":"#d1d1b6"},"text_style":{"title_size":"2.8rem","subtitle_size":"1.5rem","line_height":1.2},"custom_font":{"enable":false,"family":null,"url":null},"social_links":{"enable":false,"links":{"github":null,"instagram":null,"zhihu":null,"twitter":null,"email":null},"qrs":{"weixin":null}}},"plugins":{"feed":{"enable":false},"aplayer":{"enable":true,"type":"fixed","audios":[{"name":"起风了","artist":"买辣椒也用券","url":"https://music.163.com/song/media/outer/url?id=1330348068.mp3","cover":"https://p2.music.126.net/diGAyEmpymX8G7JcnElncQ==/109951163699673355.jpg?param=130y130"},{"name":"盗墓笔记·十年人间","artist":"青肆ToriDo","url":"https://music.163.com/song/media/outer/url?id=1298484254.mp3","cover":"https://p2.music.126.net/4vY0tPpnINMLzjV8UKywIg==/109951163438805808.jpg?param=130y130"},{"name":"囍","artist":"葛东琪","url":"https://music.163.com/song/media/outer/url?id=1303289043.mp3","cover":"https://p2.music.126.net/H3Q3SeMVtuHvHY2uyaQdOw==/109951163472855051.jpg?param=130y130"}]},"mermaid":{"enable":false,"version":"9.3.0"}},"version":"2.4.4","navbar":{"auto_hide":false,"color":{"left":"#f78736","right":"#367df7","transparency":35},"links":{"Home":{"path":"/","icon":"fa-regular fa-house"},"Memos":{"path":"/essay","icon":"fa-regular fa-lightbulb"},"Archives":{"icon":"fa-regular fa-archive","submenus":{"Archives":"/archives","Categories":"/categories","Tags":"/tags"}}},"search":{"enable":false,"preload":true}},"page_templates":{"friends_column":2,"tags_style":"blur"},"home":{"sidebar":{"enable":true,"position":"left","first_item":"menu","announcement":null,"links":null},"article_date_format":"auto","categories":{"enable":true,"limit":3},"tags":{"enable":true,"limit":3}},"footerStart":"2022/8/17 11:45:14"};
    Global.language_ago = {"second":"%s 秒前","minute":"%s 分钟前","hour":"%s 小时前","day":"%s 天前","week":"%s 周前","month":"%s 个月前","year":"%s 年前"};
    Global.data_config = {"masonry":false};
  </script>
    
    <!--- Fontawesome Part-->
    
<link rel="stylesheet" href="/jiesun.gitee.io/fontawesome/fontawesome.min.css">

    
<link rel="stylesheet" href="/jiesun.gitee.io/fontawesome/brands.min.css">

    
<link rel="stylesheet" href="/jiesun.gitee.io/fontawesome/solid.min.css">

    
<link rel="stylesheet" href="/jiesun.gitee.io/fontawesome/regular.min.css">

    
    
    
    
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
<div class="progress-bar-container">
    

    
        <span class="pjax-progress-bar"></span>
        <span class="swup-progress-icon">
            <i class="fa-solid fa-circle-notch fa-spin"></i>
        </span>
    
</div>


<main class="page-container" id="swup">

    

    <div class="main-content-container">


        <div class="main-content-header">
            <header class="navbar-container">
    
    <div class="navbar-content">
        <div class="left">
            
            <a class="logo-title" href="https://anca.gitee.io/">
                
                极乐净土
                
            </a>
        </div>

        <div class="right">
            <!-- PC -->
            <div class="desktop">
                <ul class="navbar-list">
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/jiesun.gitee.io/"  >
                                    
                                        
                                            <i class="fa-regular fa-house"></i>
                                        
                                        首页
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/jiesun.gitee.io/essay"  >
                                    
                                        
                                            <i class="fa-regular fa-lightbulb"></i>
                                        
                                        MEMOS
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="has-dropdown" 
                                    href="#" onClick="return false;">
                                    
                                        
                                            <i class="fa-regular fa-archive"></i>
                                        
                                        归档&nbsp;<i class="fa-solid fa-chevron-down"></i>
                                    
                                </a>
                                <!-- Submenu -->
                                
                                    <ul class="sub-menu">
                                    
                                        <li>
                                        <a href="/jiesun.gitee.io/archives">归档
                                        </a>
                                        </li>
                                    
                                        <li>
                                        <a href="/jiesun.gitee.io/categories">分类
                                        </a>
                                        </li>
                                    
                                        <li>
                                        <a href="/jiesun.gitee.io/tags">标签
                                        </a>
                                        </li>
                                    
                                    </ul>
                                
                            </li>
                    
                    
                </ul>
            </div>
            <!-- Mobile -->
            <div class="mobile">
                
                <div class="icon-item navbar-bar">
                    <div class="navbar-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile drawer -->
    <div class="navbar-drawer w-full absolute top-0 left-0 bg-background-color">
        <ul class="drawer-navbar-list flex flex-col justify-start items-center">
            
                
                    <li class="drawer-navbar-item text-base my-1.5 flex justify-center items-center">
                        <a class="rounded-3xl py-1.5 px-5 hover:border hover:!text-primary active:!text-primary group " 
                        href="/jiesun.gitee.io/"  >
                             
                                
                                    <i class="fa-regular fa-house"></i>
                                
                                首页
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            
                
                    <li class="drawer-navbar-item text-base my-1.5 flex justify-center items-center">
                        <a class="rounded-3xl py-1.5 px-5 hover:border hover:!text-primary active:!text-primary group " 
                        href="/jiesun.gitee.io/essay"  >
                             
                                
                                    <i class="fa-regular fa-lightbulb"></i>
                                
                                MEMOS
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            
                
                    <li class="drawer-navbar-item text-base my-1.5 flex justify-center items-center">
                        <a class="rounded-3xl py-1.5 px-5 hover:border hover:!text-primary active:!text-primary group has-dropdown" 
                        href="#" onClick="return false;">
                            
                                
                                    <i class="fa-regular fa-archive"></i>
                                
                                归档&nbsp;<i class="group-hover:rotate-180 transition-transform fa-solid fa-chevron-down"></i>
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                              
                        
                            <li class="text-base flex justify-center items-center hover:underline active:underline hover:underline-offset-1 rounded-3xl">
                                <a class="py-0.5" href="/jiesun.gitee.io/archives">归档</a>
                            </li>
                        
                            <li class="text-base flex justify-center items-center hover:underline active:underline hover:underline-offset-1 rounded-3xl">
                                <a class="py-0.5" href="/jiesun.gitee.io/categories">分类</a>
                            </li>
                        
                            <li class="text-base flex justify-center items-center hover:underline active:underline hover:underline-offset-1 rounded-3xl">
                                <a class="py-0.5" href="/jiesun.gitee.io/tags">标签</a>
                            </li>
                        
                    
            

        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="main-content-body">

            

            <div class="main-content">

                
                    <div class="post-page-container">
    <div class="article-content-container">

        <div class="article-title">
            
                
                
                <img src="https://anca.gitee.io/jiesun.gitee.io/images/bg4.jpeg" alt="搞懂模块化" class="max-w-none"/>
                
                <h1 class="article-title-cover">搞懂模块化</h1>
            
            </div>
            
                    
        
        
            <div class="article-header">
                <div class="avatar">
                    <img src="/jiesun.gitee.io/images/redefine-avatar.svg">
                </div>
                <div class="info">
                    <div class="author">
                        <span class="name">jiesun</span>
                        
                            <span class="author-label">Lv3</span>
                        
                    </div>
                    <div class="meta-info">
                        <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fa-regular fa-pen-fancy"></i>&nbsp;
        <span class="desktop">2023-11-04 14:50:37</span>
        <span class="mobile">2023-11-04 14:50:37</span>
        <span class="hover-info">创建</span>
    </span>
    
        <span class="article-date article-meta-item">
            <i class="fa-regular fa-wrench"></i>&nbsp;
            <span class="desktop">2023-11-04 15:31:15</span>
            <span class="mobile">2023-11-04 15:31:15</span>
            <span class="hover-info">更新</span>
        </span>
    

    
        <span class="article-categories article-meta-item">
            <i class="fa-regular fa-folders"></i>&nbsp;
            <ul>
                
                
                    
                        
                        <li>
                            <a href="/jiesun.gitee.io/categories/js/">js</a>&nbsp;
                        </li>
                    
                    
                
            </ul>
        </span>
    
    

    
    
    
    
        <span class="article-pv article-meta-item">
            <i class="fa-regular fa-eye"></i>&nbsp;<span id="busuanzi_value_page_pv"></span>
        </span>
    
</div>

                    </div>
                </div>
            </div>
        

        


        <div class="article-content markdown-body">
            <h1 id="js模块化方案"><a href="#js模块化方案" class="headerlink" title="js模块化方案"></a>js模块化方案</h1><h2 id="CommonJS："><a href="#CommonJS：" class="headerlink" title="CommonJS："></a>CommonJS：</h2><blockquote>
<p>这是一个由Node.js社区推动的模块化方案，它使用同步的require和module.exports来定义模块。CommonJS在浏览器端使用时会有一些问题，因为它不支持异步加载和动态的模块定义。</p>
</blockquote>
<div class="highlight-container" data-rel="Js"><figure class="iseeu highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 集中一起导出</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">  <span class="attr">userName</span>: <span class="string">&#x27;前端&#x27;</span>,</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 或分散导出</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span>.<span class="property">userName</span> = <span class="string">&#x27;前端&#x27;</span>;</span><br><span class="line"><span class="comment">// 或</span></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">userName</span> = <span class="string">&#x27;前端&#x27;</span>; </span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Setting</span> = <span class="built_in">require</span>(<span class="string">&#x27;./user&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 或用解构写法，直接提取属性</span></span><br><span class="line"><span class="keyword">const</span> &#123; userName &#125; = <span class="built_in">require</span>(<span class="string">&#x27;./user&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 或不使用任何导出内容，但希望指定对应模块文件的副作用（如给全局注入变量）</span></span><br><span class="line"><span class="built_in">require</span>(<span class="string">&#x27;./user&#x27;</span>);</span><br></pre></td></tr></table></figure></div>
<p>每个文件都可以访问到一个 module 对象，其下的 exports 属性是一个空对象，你可以给它加上属性，module.exports 将作为可以导出的代码部分。</p>
<p>exports 是一个别名，它指向 module.exports。</p>
<h2 id="ESM："><a href="#ESM：" class="headerlink" title="ESM："></a>ESM：</h2><blockquote>
<p>这是由ECMAScript标准定义的模块系统，它使用import和export关键字来定义模块。ES6模块在浏览器端和Node.js环境中都可以使用，并且支持异步加载和动态的模块定义。</p>
</blockquote>
<div class="highlight-container" data-rel="Jsx"><figure class="iseeu highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入需要的变量</span></span><br><span class="line"><span class="keyword">import</span> &#123; userName &#125; <span class="keyword">from</span> <span class="string">&#x27;./user.js&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导入 export default 对应的变量，这时候不需要花括号</span></span><br><span class="line"><span class="keyword">import</span> user <span class="keyword">from</span> <span class="string">&#x27;./user.js&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在命名冲突时，可以给导入的变量换个名字</span></span><br><span class="line"><span class="keyword">import</span> user <span class="keyword">as</span> otherUser <span class="keyword">from</span> <span class="string">&#x27;./user.js&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 将 export 组装成对象，包括 export default，对应 default 属性名</span></span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> obj <span class="keyword">from</span> <span class="string">&#x27;./user.js&#x27;</span> </span><br></pre></td></tr></table></figure></div>
<h1 id="区别"><a href="#区别" class="headerlink" title="区别"></a>区别</h1><p>1.语法：CommonJS 使用的是同步的语法，例如 module.exports 和 require()，而 ES Modules 使用的是异步的语法，例如 import 和 export。这意味着 ES Modules 可以实现更加灵活的模块加载和引用方式。<br>2.加载机制：CommonJS 模块在加载时是按顺序执行，会将整个模块加载完毕后才能使用。而 ES Modules 在加载时是按需加载，可以只加载需要的模块，减轻了服务器的负担，并加快了页面加载速度。<br>3.运行时行为：在 CommonJS 中，module.exports 输出的模块接口是一个对象，所有的模块内部变量都挂载在这个对象上面。而在 ES Modules 中，export 输出的模块接口是一个值的引用，模块内部的变量不会挂载在任何对象上面，因此修改这个变量的值不会影响其他模块。<br>4.静态编译：ES Modules 在编译期间就能确定模块的依赖关系，而 CommonJS 是在运行时加载模块，因此 ES Modules 可以实现更好的静态优化和缓存。<br>5.适用范围：由于 ES Modules 的异步特性和静态编译优势，它更适合浏览器环境，而 CommonJS 更适合服务器端环境。然而，随着 Node.js 的不断进化，CommonJS 也已经能够支持 ES Modules 的大部分特性</p>
<h1 id="webpack-（commonjs）"><a href="#webpack-（commonjs）" class="headerlink" title="webpack （commonjs）"></a>webpack （commonjs）</h1><p>其实现在内置esm了，在没有内置之前，使用bable 将esm的import 转换成 require 等commonjs</p>
<p>优点：</p>
<p>适合大型项目：Webpack具有强大的打包能力，可以处理大型项目的多个模块，并且可以优化构建速度和代码分割。<br>插件丰富：Webpack拥有丰富的插件生态，可以满足各种不同的需求，例如打包优化、代码压缩、热更新等。<br>社区支持：Webpack是JavaScript社区中最流行的打包工具之一，具有广泛的社区支持和文档。<br>缺点：</p>
<p>打包速度慢：由于Webpack在打包时需要分析模块依赖、编译等操作，导致打包速度相对较慢。<br>学习成本高：Webpack的配置相对复杂，需要一定的学习成本才能掌握。<br>体积大：Webpack的体积相对较大，可能会增加用户的加载时间和流量消耗。</p>
<h1 id="vite-（esm）"><a href="#vite-（esm）" class="headerlink" title="vite （esm）"></a>vite （esm）</h1><p>vite直接基于esm实现模块化<br>优点：<br>启动速度快：Vite采用ESM进行模块化，无需打包即可直接使用模块，启动速度非常快。<br>按需编译：Vite在开发模式下会对模块进行按需编译，可以减少打包时间和流量消耗。<br>适合现代浏览器：Vite基于ESM，更适合现代浏览器环境。<br>插件生态逐渐丰富：虽然Vite的插件生态没有Webpack丰富，但随着时间的推移，越来越多的插件开始支持Vite。<br>缺点：<br>生产环境下构建能力较弱：Vite在生产环境下的构建能力相对较弱，没有Webpack那么丰富的优化选项。<br>生态不够完善：虽然Vite的插件生态正在逐渐丰富，但相比Webpack还是有一定的差距。一些常用的库和插件可能还没有完全支持Vite。<br>需要额外配置：Vite需要额外的配置才能支持一些特定的功能，例如代码分割、热更新等。这可能会增加开发者的学习成本。</p>
<p>以上 vite 和 webpack的优缺点都是大模型给的，但是我现在经历的项目 用vite已经绰绰有余，自动挡方便</p>
<h1 id="编译过程"><a href="#编译过程" class="headerlink" title="编译过程"></a>编译过程</h1><p>Webpack的编译过程可以概括为四个阶段：入口点分析、依赖图分析、模块转换和打包输出。</p>
<p>入口点分析：Webpack将一个或多个入口点作为输入，入口点是Webpack构建过程的起点。Webpack通过分析入口点来确定所有需要打包的模块。在Webpack中，一个入口点可以是一个JavaScript文件、一个CSS文件、一个HTML文件，甚至可以是一个Markdown文件。Webpack默认情况下会在项目根目录下寻找一个名为index.js的JavaScript文件作为入口点。Webpack通过解析入口点中的代码来确定需要打包的模块，这个过程称为入口点分析。入口点分析的过程中，Webpack会检查入口点中导入的模块，以此确定整个依赖关系图。Webpack使用acorn这个JavaScript解析器来解析入口点中的代码，并根据代码中的导入语句和导出语句来构建依赖关系图。<br>依赖图分析：在入口点分析完成之后，Webpack会开始对依赖关系图进行分析，以此确定所有需要打包的模块。Webpack会遍历依赖关系图，递归地查找所有的模块，并将它们打包到最终的输出文件中。依赖图分析的过程中，Webpack会根据模块的类型和配置选项来确定如何处理每一个模块。例如，如果一个模块是一个JavaScript文件，Webpack会使用Babel将其转换为ES5代码，并使用UglifyJS压缩代码。如果一个模块是一个CSS文件，Webpack会使用PostCSS处理它，并将它打包到最终的输出文件中。在依赖图分析的过程中，Webpack还会处理模块之间的循环依赖关系。当Webpack遇到一个循环依赖关系时，它会使用一个特殊的技巧来解决这个问题。<br>模块转换：Webpack会对每个模块进行转换，这个过程涉及到解析模块的语法和结构，以及执行一些转换操作。例如，对于ES6模块，Webpack会将其转换为ES5代码，以便在旧版本的浏览器上运行。此外，Webpack还可以使用插件来对模块进行自定义转换操作。<br>打包输出：最后，Webpack会将所有模块打包成一个或多个输出文件，这些文件将被用于在浏览器中执行。Webpack提供了许多选项来控制输出文件的命名、位置和内容等。<br>Vite的编译过程与Webpack有所不同。Vite基于ESM进行构建，它充分利用了现代浏览器的ESM特性，将开发环境下的模块文件直接作为浏览器要执行的文件，而不是像Webpack那样先进行打包。具体来说，Vite的编译过程如下：</p>
<p>启动开发服务器：Vite直接启动开发服务器，然后按需编译依赖文件。由于现代浏览器本身就支持ESM，因此当请求某个模块时，Vite会实时编译该模块并将其发送到浏览器中。这种按需编译的方式大大提高了开发速度。<br>实时编译：Vite使用ESM实时编译模块。当浏览器请求某个模块时，Vite会先检查是否有缓存版本可用，如果缓存版本不存在，则会使用ESM将其转换为可以在浏览器中执行的代码。这个过程是实时的，因此可以立即在浏览器中看到更改的效果。<br>缓存优化：Vite使用ESM的缓存机制来提高编译效率。ESM在第一次请求某个模块时进行编译，并在后续请求时直接使用缓存结果，这样可以避免重复编译相同的模块。Vite还会根据文件的更改情况来更新缓存，确保编译结果的正确性和实时性。<br>代码分割和懒加载：Vite支持代码分割和懒加载功能，可以将代码拆分成多个文件，并根据需求进行按需加载。这样可以减少初始加载时间，提高应用程序的性能。<br>插件支持：Vite支持使用插件来扩展功能。插件可以用于优化构建结果、压缩代码、添加自定义转换操作等。这使得Vite具有很高的可扩展性和灵活性。<br>总之，Webpack和Vite的编译过程存在明显的差异。Webpack更注重打包优化和代码转换，而Vite更注重实时编译和缓存优化。在实际应用中，可以根据项目需求和开发环境选择合适的工具来提高构建效率和开发速度。</p>

        </div>

        
            <div class="post-copyright-info">
                <div class="article-copyright-info-container">
    <ul>
        <li><strong>标题:</strong> 搞懂模块化</li>
        <li><strong>作者:</strong> jiesun</li>
        <li><strong>创建于
                :</strong> 2023-11-04 14:50:37</li>
        
            <li>
                <strong>更新于
                    :</strong> 2023-11-04 15:31:15
            </li>
        
        <li>
            <strong>链接:</strong> https://anca.gitee.io/jiesun.gitee.io/2023/11/04/module/
        </li>
        <li>
            <strong>
                版权声明:
            </strong>
            
            本文章采用 <a class="license" target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0</a> 进行许可。
            

        </li>
    </ul>
</div>

            </div>
        

        

        

        
            <div class="article-nav">
                
                
                    <div class="article-next">
                        <a class="next"
                        rel="next"
                        href="/jiesun.gitee.io/2023/10/30/vue3-4/"
                        >
                            <span class="title flex justify-center items-center">
                                <span class="post-nav-title-item">vue3 源码分析（4）- 生成虚拟 DOM</span>
                                <span class="post-nav-item">下一篇</span>
                            </span>
                            <span class="right arrow-icon flex justify-center items-center">
                                <i class="fa-solid fa-chevron-right"></i>
                            </span>
                        </a>
                    </div>
                
            </div>
        


        
    </div>

    
        <div class="toc-content-container">
            <div class="post-toc-wrap">
    <div class="post-toc">
        <div class="toc-title">此页目录</div>
        <div class="page-title">搞懂模块化</div>
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#js%E6%A8%A1%E5%9D%97%E5%8C%96%E6%96%B9%E6%A1%88"><span class="nav-text">js模块化方案</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#CommonJS%EF%BC%9A"><span class="nav-text">CommonJS：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ESM%EF%BC%9A"><span class="nav-text">ESM：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8C%BA%E5%88%AB"><span class="nav-text">区别</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#webpack-%EF%BC%88commonjs%EF%BC%89"><span class="nav-text">webpack （commonjs）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#vite-%EF%BC%88esm%EF%BC%89"><span class="nav-text">vite （esm）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BC%96%E8%AF%91%E8%BF%87%E7%A8%8B"><span class="nav-text">编译过程</span></a></li></ol>

    </div>
</div>
        </div>
    
</div>



                

            </div>

            

        </div>

        <div class="main-content-footer">
            <footer class="footer mt-5 py-5 h-auto text-base text-third-text-color relative border-t-2 border-t-border-color">
    <div class="info-container py-3 text-center">
        
        <div class="text-center">
            &copy;
            
              <span>2022</span>
              -
            
            2023&nbsp;&nbsp;<i class="fa-solid fa-heart fa-beat" style="--fa-animation-duration: 0.5s; color: #f54545"></i>&nbsp;&nbsp;<a href="/">jiesun</a>
        </div>
        
            <script data-swup-reload-script src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
            <div class="relative text-center lg:absolute lg:right-[20px] lg:top-1/2 lg:-translate-y-1/2 lg:text-right">
                
                    <span id="busuanzi_container_site_uv" class="lg:!block">
                        <span class="text-sm">访问人数</span>
                        <span id="busuanzi_value_site_uv"></span>
                    </span>
                
                
                    <span id="busuanzi_container_site_pv" class="lg:!block">
                        <span class="text-sm">总访问量</span>
                        <span id="busuanzi_value_site_pv"></span>
                    </span>
                
            </div>
        
        <div class="relative text-center lg:absolute lg:left-[20px] lg:top-1/2 lg:-translate-y-1/2 lg:text-left">
            <span class="lg:block text-sm">由 <?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg class="relative top-[2px] inline-block align-baseline" version="1.1" id="圖層_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1rem" height="1rem" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path fill="#0E83CD" d="M256.4,25.8l-200,115.5L56,371.5l199.6,114.7l200-115.5l0.4-230.2L256.4,25.8z M349,354.6l-18.4,10.7l-18.6-11V275H200v79.6l-18.4,10.7l-18.6-11v-197l18.5-10.6l18.5,10.8V237h112v-79.6l18.5-10.6l18.5,10.8V354.6z"/></svg><a target="_blank" class="text-base" href="https://hexo.io">Hexo</a> 驱动</span>
            <span class="text-sm lg:block">主题&nbsp;<a class="text-base" target="_blank" href="https://github.com/EvanNotFound/hexo-theme-redefine">Redefine v2.4.4</a></span>
        </div>
        
        
            <div>
                博客已运行 <span class="odometer" id="runtime_days" ></span> 天 <span class="odometer" id="runtime_hours"></span> 小时 <span class="odometer" id="runtime_minutes"></span> 分钟 <span class="odometer" id="runtime_seconds"></span> 秒
            </div>
        
        
            <script data-swup-reload-script>
                try {
                    function odometer_init() {
                    const elements = document.querySelectorAll('.odometer');
                    elements.forEach(el => {
                        new Odometer({
                            el,
                            format: '( ddd).dd',
                            duration: 200
                        });
                    });
                    }
                    odometer_init();
                } catch (error) {}
            </script>
        
        
        
    </div>  
</footer>
        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="article-tools-list">
        <!-- TOC aside toggle -->
        
            <li class="right-bottom-tools page-aside-toggle">
                <i class="fa-regular fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
    </ul>
</div>

        </div>
    

    <div class="right-side-tools-container">
        <div class="side-tools-container">
    <ul class="hidden-tools-list">
        <li class="right-bottom-tools tool-font-adjust-plus flex justify-center items-center">
            <i class="fa-regular fa-magnifying-glass-plus"></i>
        </li>

        <li class="right-bottom-tools tool-font-adjust-minus flex justify-center items-center">
            <i class="fa-regular fa-magnifying-glass-minus"></i>
        </li>

        <li class="right-bottom-tools tool-expand-width flex justify-center items-center">
            <i class="fa-regular fa-expand"></i>
        </li>

        <li class="right-bottom-tools tool-dark-light-toggle flex justify-center items-center">
            <i class="fa-regular fa-moon"></i>
        </li>

        <!-- rss -->
        

        

        <li class="right-bottom-tools tool-scroll-to-bottom flex justify-center items-center">
            <i class="fa-regular fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="visible-tools-list">
        <li class="right-bottom-tools toggle-tools-list flex justify-center items-center">
            <i class="fa-regular fa-cog fa-spin"></i>
        </li>
        
            <li class="right-bottom-tools tool-scroll-to-top flex justify-center items-center">
                <i class="arrow-up fas fa-arrow-up"></i>
                <span class="percent"></span>
            </li>
        
        
    </ul>
</div>

    </div>

    <div class="image-viewer-container">
    <img src="">
</div>


    

</main>


    
<script src="/jiesun.gitee.io/js/libs/Swup.min.js"></script>

<script src="/jiesun.gitee.io/js/libs/SwupSlideTheme.min.js"></script>

<script src="/jiesun.gitee.io/js/libs/SwupScriptsPlugin.min.js"></script>

<script src="/jiesun.gitee.io/js/libs/SwupProgressPlugin.min.js"></script>

<script src="/jiesun.gitee.io/js/libs/SwupScrollPlugin.min.js"></script>

<script>
    const swup = new Swup({
        plugins: [
            new SwupScriptsPlugin({
                optin: true,
            }),
            new SwupProgressPlugin(),
            new SwupScrollPlugin({
                offset: 80,
            }),
            new SwupSlideTheme({
                mainElement: ".main-content-body",
            }),
        ],
        containers: ["#swup"],
    });

    swup.hooks.on("page:view", () => {
        Global.refresh();
    });

    // if (document.readyState === "complete") {
    //
    // } else {
    //     document.addEventListener("DOMContentLoaded", () => init());
    // }
</script>






<script src="/jiesun.gitee.io/js/utils.js" type="module"></script>

<script src="/jiesun.gitee.io/js/main.js" type="module"></script>

<script src="/jiesun.gitee.io/js/layouts/navbarShrink.js" type="module"></script>

<script src="/jiesun.gitee.io/js/tools/scrollTopBottom.js" type="module"></script>

<script src="/jiesun.gitee.io/js/tools/lightDarkSwitch.js" type="module"></script>

<script src="/jiesun.gitee.io/js/layouts/categoryList.js" type="module"></script>





    
<script src="/jiesun.gitee.io/js/tools/codeBlock.js"></script>




    
<script src="/jiesun.gitee.io/js/layouts/lazyload.js"></script>




    
<script src="/jiesun.gitee.io/js/tools/runtime.js"></script>

    
<script src="/jiesun.gitee.io/js/libs/odometer.min.js"></script>

    
<link rel="stylesheet" href="/jiesun.gitee.io/assets/odometer-theme-minimal.css">




  
<script src="/jiesun.gitee.io/js/libs/Typed.min.js"></script>

  
<script src="/jiesun.gitee.io/js/plugins/typed.js"></script>







<div class="post-scripts" data-swup-reload-script>
    
        
<script src="/jiesun.gitee.io/js/libs/anime.min.js"></script>

        
<script src="/jiesun.gitee.io/js/tools/tocToggle.js" type="module"></script>

<script src="/jiesun.gitee.io/js/layouts/toc.js" type="module"></script>

<script src="/jiesun.gitee.io/js/plugins/tabs.js" type="module"></script>

    
</div>


    <div id="aplayer"></div>

<script src="/jiesun.gitee.io/js/libs/APlayer.min.js"></script>


<script src="/jiesun.gitee.io/js/plugins/aplayer.js"></script>


</body>
</html>
